from django.shortcuts import render, HttpResponse, redirect
from app02.forms import EmpForm
from app02 import models
from django.core.exceptions import ValidationError


# Create your views here.


def add_emp(request):
    if request.method == "GET":
        form = EmpForm()
        return render(request, "add_emp.html", {"form": form})
    else:
        form = EmpForm(request.POST)  # 将数据传给form对象
        if form.is_valid():  # 进行数据校验
            # 校验成功
            data = form.cleaned_data  # 校验成功的值，会放在cleaned_data里。
            data.pop('r_salary')
            print(data)

            models.Emp.objects.create(**data)
            # return redirect("/index/")
            # return HttpResponse('ok')
            return render(request, "add_emp.html", {"form": form})
        else:
            print(form.errors)  # 打印错误信息
            clean_errors = form.errors.get("__all__")  # 获取全局钩子错误信息
            print(222, clean_errors)
        return render(request, "add_emp.html", {"form": form, "clean_errors": clean_errors})
